package com.sj.uabrowser;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import com.sj.uabrowser.adp.MyPagerAdapter;
import com.sj.uabrowser.app.Constant;
import com.sj.uabrowser.app.NetworkUtils;
import com.sj.uabrowser.app.SPUtil;
import com.sj.uabrowser.app.StatusBarUtil;
import com.sj.uabrowser.app.TianqiIconUtil;
import com.sj.uabrowser.app.Util;
import com.sj.uabrowser.app.ViewUtil;
import com.sj.uabrowser.db.CollectHistory;
import com.sj.uabrowser.db.TabRecrd;
import com.sj.uabrowser.db.gen.CollectHistoryDao;
import com.sj.uabrowser.db.gen.TabRecrdDao;
import com.sj.uabrowser.framework.BaseActivity;
import com.sj.uabrowser.meta.MyViewPager;
import com.sj.uabrowser.meta.UCTabCard;
import com.sj.uabrowser.mvp.main.bean.HomeTab;
import com.sj.uabrowser.mvp.main.bean.MainNewFuncs;
import com.sj.uabrowser.mvp.main.bean.PageBean;
import com.sj.uabrowser.mvp.main.contract.MainContract;
import com.sj.uabrowser.mvp.main.presenter.MainPresenter;
import com.sj.uabrowser.mvp.main.utils.LocationService;
import com.sj.uabrowser.mvp.main.view.act.SearchAct;
import com.sj.uabrowser.mvp.main.view.act.TextAct;
import com.sj.uabrowser.mvp.main.view.adp.MyCustomPagerAdapter;
import com.sj.uabrowser.mvp.main.view.adp.OperAdp;
import com.sj.uabrowser.mvp.main.view.adp.UCTabAdapter;
import com.sj.uabrowser.mvp.main.view.fragment.NavFuncsFragment;
import com.sj.uabrowser.mvp.main.view.fragment.NewsFragment;
import com.sj.uabrowser.mvp.menu.view.act.CollectAct;
import com.sj.uabrowser.mvp.menu.view.act.DownloadAct;
import com.sj.uabrowser.mvp.menu.view.act.HistoryAct;
import com.sj.uabrowser.mvp.settings.view.act.SettingsAct;
import com.sj.uabrowser.mvp.share.ResourcesManager;
import com.sj.uabrowser.mvp.share.tencent.qq.QQShare;
import com.sj.uabrowser.mvp.share.tencent.qzone.QQZoneShare;
import com.sj.uabrowser.mvp.share.wechat.friends.WechatShare;
import com.sj.uabrowser.mvp.share.wechat.moments.WechatMomentsShare;
import com.sj.uabrowser.mvp.video.view.fragment.VideoListFragment;
import com.sj.uabrowser.mvp.wea.bean.MainContent;
import com.sj.uabrowser.net.bean.Oper;
import com.sj.uabrowser.web.BrowserWebViewFactory;
import com.sj.uabrowser.web.Tab;
import com.sj.uabrowser.web.TabController;
import com.sj.uabrowser.web.UiController;
import com.sj.uabrowser.web.WebViewFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.common.Const;
import com.vondear.rxfeature.activity.ActivityScanerCode;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxNetTool;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;
import com.zibuyuqing.stackview.widget.UCStackView;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

public class MainActivity extends BaseActivity<MainContract.Presenter> implements MainContract.View, CompoundButton.OnCheckedChangeListener,
        UCStackView.OnChildDismissedListener,
        UiController, TabLayout.BaseOnTabSelectedListener, View.OnClickListener, PlatformActionListener {

    private static final int REQUESTCODE_SCANCODE = 1;
    private static final int REQUESTCODE_SEARCH = 2;
    private static final int REQUESTCODE_SETTINGS = 3;
    private static final int REQUESTCODE_SEARCHACT = 4;
    private static final int REQUESTCODE_NETSETTTINS = 5;

    public static boolean mIsScroll = true;

    @BindView(R.id.iv_loc)
    ImageView ivLoc;
    @BindView(R.id.video_full_container)
    public FrameLayout videoFullContainer;
    @BindView(R.id.navFuncs)
    ViewPager navFuncs;
    @BindView(R.id.rbtn_main)
    CheckBox rbtnMain;
    @BindView(R.id.rbtn_video)
    CheckBox rbtnVideo;
    @BindView(R.id.rbtn_menu)
    CheckBox rbtnMenu;
    @BindView(R.id.rbtn_multi)
    CheckBox rbtnMulti;
    @BindView(R.id.tv_caidan_multi)
    TextView tvCaidanMulti;
    // 悬浮搜索条 webview加载后出现

    @BindView(R.id.floatSearchBar)
    LinearLayout mFloatSearchBar;
    @BindView(R.id.tvFloatSearchTitle)
    TextView mTvFloatSearchTitle;

    @BindView(R.id.etFloatSearchTitle)
    EditText mEtFloatSearchTitle;

    @BindView(R.id.ivFloatSearchRefresh)
    ImageView mIvFloatSearchRefresh;

    @BindView(R.id.pbFloatSearchProgress)
    ProgressBar mFloatSearchProgress;

    @BindView(R.id.homeContentWrapper)
    FrameLayout mContentWrapper;
    //    @BindView(R.id.ucRootView)
//    UCRootView mUCRootView;
    @BindView(R.id.mCoordinatorLayout)
    CoordinatorLayout mUCRootView;
    @BindView(R.id.ucStackView)
    UCStackView mUCStackView;
    // 底部菜单
    @BindView(R.id.llUCBottomBar)
    LinearLayout mUCBottomBar;
    @BindView(R.id.flPagersManager)
    FrameLayout mTabsManagerLayout;//多窗口
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
//    @BindView(R.id.toobar2)
//    Toolbar toolbar2;
    @BindView(R.id.rl_search2)
    RelativeLayout rlSearch2;
    @BindView(R.id.viewpager)
    MyViewPager viewPager;
    @BindView(R.id.appBarLayout)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.ll_appbarcontent)
    View ll_appbarcontent;
    @BindView(R.id.fl_video_container)
    FrameLayout flVideoContainer;
    @BindView(R.id.iv_weather)
    ImageView ivWeather;
    @BindView(R.id.tv_cur_temp)
    TextView tvCurTemp;
    @BindView(R.id.tv_wearth)
    TextView tvWearth;
    @BindView(R.id.tv_contry)
    TextView tvContry;
    @BindView(R.id.tv_temp_location)
    TextView tvTempLocation;
    @BindView(R.id.rl_weather)
    RelativeLayout rlWeather;
    @BindView(R.id.ll_browser_oper)
    LinearLayout llBrowserOper;

    private int mAppBarHeight, statusbarHeight;

    private boolean mTabsManagerUIShown = false;

    TabController mTabController;
    private Tab mActiveTab;
    private WebViewFactory mFactory;
    private boolean mIsAnimating = false;
    private boolean mIsInMain = true;

    private int[] iconRes = {R.mipmap.zixun_unselected, R.mipmap.shipin_unselected, R.mipmap.caidan_unselected};
    private int[] iconResSelected = {R.mipmap.zixun_selected, R.mipmap.shipin_selected, R.mipmap.caidan_selected};
    private String[] textRes = {"首页", "视频", "菜单"};

    private List<Fragment> fragments = new ArrayList<>();
    private MyCustomPagerAdapter adp;
    UCTabAdapter mTabAdapter;
    private List<Tab> mTabs = new ArrayList<>();
    @BindView(R.id.tvPagerNum)
    TextView mTabNum;

    public Tab getAcitiveTab() {
        return mActiveTab;
    }

    private ArrayList<MainNewFuncs.AdListBean> mainFuncs = new ArrayList<>();
    int spanCount = 6;//主功能列数
    List<Fragment> fsNavFuncs = new ArrayList<>();
    private int fontSize = 15;

    public LocationService locationService;

    @OnClick(R.id.tvFloatSearchTitle)
    public void onSearchClick(View view) {
        Intent intent = new Intent(this, SearchAct.class);
        intent.putExtra("url", mActiveTab.getWebView().getUrl());
        startActivityForResult(intent, REQUESTCODE_SEARCHACT);
    }

    @OnClick(R.id.tv_temp_location)
    public void onTempLocation(View view) {
        startIconAnim(view);
        if (!RxNetTool.isNetworkAvailable(this)) {
            startActivityForResult(new Intent(
                    android.provider.Settings.ACTION_WIRELESS_SETTINGS), REQUESTCODE_NETSETTTINS);
        } else {
            requestWeather();
        }
    }


    @Override
    public MainContract.Presenter createPresenter() {
        return new MainPresenter(this);
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_main;
    }

    private String searchUrl;

    @OnClick({R.id.rl_search, R.id.rl_search2})
    public void onSearch() {
        if (TextUtils.isEmpty(searchUrl)) {
            searchUrl = "http://m.baidu.com/s?from=1022925z&word=";
        }
        Intent intent = new Intent(this, SearchAct.class);
        intent.putExtra("searchUrl", searchUrl);// "http://m.baidu.com/s?from=1022925z&word="
        startActivityForResult(intent, REQUESTCODE_SEARCH);
    }

    boolean scanClicked = false;

    @OnClick({R.id.iv_scancode, R.id.iv_scancode2})
    public void onScan(View view) {
        if (!scanClicked) {
            if (BuildConfig.UM) {
                String eventid = "scan-search";
                MobclickAgent.onEvent(MainActivity.this, eventid, "扫描-搜索");
            }
            scanClicked = true;
            startIconAnim(view);
            rxPermissions.request(Manifest.permission.CAMERA)
                    .subscribe(grant -> {
                        if (grant) {
                            RxActivityTool.skipActivityForResult(this, ActivityScanerCode.class, REQUESTCODE_SCANCODE);
                        } else {
                            RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(MainActivity.this);
                            rxDialogSureCancel.setTitle("提示");
                            rxDialogSureCancel.setContent("没有开启调用摄像头权限，无法扫描二维码，确定开启吗？");
                            rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    rxPermissions.request(Manifest.permission.CAMERA)
                                            .subscribe(grant -> {
                                                if (grant) {
                                                    RxActivityTool.skipActivityForResult(MainActivity.this, ActivityScanerCode.class, REQUESTCODE_SCANCODE);
                                                }
                                            });
                                    rxDialogSureCancel.dismiss();
                                }
                            });
                            rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    rxDialogSureCancel.dismiss();
                                }
                            });
                        }
                    });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_NETSETTTINS) {
            requestWeather();
        } else if (requestCode == REQUESTCODE_SCANCODE) {
            scanClicked = false;
            if (data != null) {
                String barCode = data.getStringExtra("barCode");
                if (!TextUtils.isEmpty(barCode)) {
                    barCode = barCode.trim();
                    if (isUrl(barCode)) {
                        if (!barCode.startsWith("http")) {
                            barCode = "https://" + barCode;
                        }
                        load(barCode);
//                        Intent intent = new Intent(MainActivity.this, SearchAct.class);
//                        intent.putExtra("httpurl", barCode);
//                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(MainActivity.this, TextAct.class);
                        intent.putExtra("text", barCode);
                        startActivityForResult(intent, -1);
                    }
                }
            }
        } else if (requestCode == REQUESTCODE_SETTINGS) {
            int newFontSize = SPUtil.get(MainActivity.this, SPUtil.KEY_FONTSIZE, fontSize);
            if (fontSize != newFontSize) {
                int curIdx = viewPager.getCurrentItem();
                try {
                    if (curIdx < fragments.size()) {
                        NewsFragment newsFragment = (NewsFragment) fragments.get(curIdx);
                        if (newsFragment != null) newsFragment.updateFontSize();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == REQUESTCODE_SEARCHACT || requestCode == REQUESTCODE_SEARCH) {
            if (resultCode == SearchAct.RESULTCODE_KEYWORDS) {
                String content = data.getStringExtra("keywords");
//                mActiveTab.getWebView().loadUrl(searchUrl+content);
                load(searchUrl + content);
            } else if (resultCode == SearchAct.RESULTCODE_WEBSITE) {
                String url = data.getStringExtra("url");
//                mActiveTab.getWebView().loadUrl(url);
                load(url);
            }
        }
    }

    String addrStr, district;
    private BDAbstractLocationListener listener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (!TextUtils.isEmpty(addrStr)) return;
            if (bdLocation != null && bdLocation.getDistrict() != null) {
                Logger.e("获取到定位");
                addrStr = bdLocation.getAddrStr();
                try {
                    if (!TextUtils.isEmpty(addrStr)) {
                        district = bdLocation.getDistrict();
                        presenter.fetchCityId(bdLocation.getProvince(), bdLocation.getCity(), bdLocation.getDistrict());
                    }
                } catch (Exception e) {
                }
            }
        }
    };

    @Override
    public void onStop() {
        super.onStop();
        if (locationService != null)
            locationService.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (locationService != null)
            locationService.unregisterListener(listener);
    }

    TabRecrdDao tabRecrdDao;

    @Override
    public void setView() {
        Logger.e("density:" + Util.getDisplayMetrics().density);
        collectHistoryDao = daoSession.getCollectHistoryDao();
        tabRecrdDao = daoSession.getTabRecrdDao();
        locationService = new LocationService(this);
        locationService.registerListener(listener);
        locationService.start(this);
        StatusBarUtil.setTransparentForImageViewInFragment(this, null);//setTransparentForImageViewInFragment   setTransparentForImageView
        StatusBarUtil.setLightMode(this);

        updateAppbarHeight();

        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public synchronized void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset != 0) {
                    Logger.e("verticalOffset:" + verticalOffset + ",mAppBarHeight:" + (-mAppBarHeight));//646    + Util.transPX(80)
//                    if ((Math.abs(verticalOffset) - mAppBarHeight>0 &&Math.abs(verticalOffset) - mAppBarHeight<5)||(Math.abs(verticalOffset) - mAppBarHeight>50 &&Math.abs(verticalOffset) - mAppBarHeight<55)) {
//                        Logger.e("xxxxxx");
//                        rbtnMain.setChecked(true);
//                    }

                    if (verticalOffset == -mAppBarHeight || verticalOffset < -mAppBarHeight-Util.transPX(30)) {
                        Logger.e("xxxxxx");

//                        mAppBarLayout.setExpanded(false,false);
                        rbtnMain.setChecked(true);
                    }
                }

            }
        });
        resManager = ResourcesManager.getInstace(this);
        mTabController = new TabController(this, this);
        mFactory = new BrowserWebViewFactory(this);

        List<TabRecrd> tabRecrds = tabRecrdDao.loadAll();
        for (int i = 0; i < tabRecrds.size(); i++) {
            Tab tab = buildTab();
            Bundle state = new Bundle();
            TabRecrd tabrecrd = tabRecrds.get(i);

            state.putLong(Tab.ID, tabrecrd.getId());
            String url = tabrecrd.getUrl();
            state.putString(Tab.CURRENT_URL, url);
            state.putString(Tab.CURRENT_TITLE, tabrecrd.getTilte());
            tab.restoreState(state);
            if (!TextUtils.isEmpty(url)) mTabs.add(tab);
            else tabRecrdDao.delete(tabrecrd);
        }

        // 先建立一个tab标记主页
//        if (mTabController.getTabCount() <= 0) {
        addTab(false);
//            if(tabRecrds.size()>0) {
//                Bundle state = new Bundle();
//                state.putLong(Tab.ID,tabRecrds.get(tabRecrds.size() - 1).getId());
//                state.putString(Tab.CURRENT_URL, tabRecrds.get(tabRecrds.size() - 1).getUrl());
//                state.putString(Tab.CURRENT_TITLE, tabRecrds.get(tabRecrds.size() - 1).getTilte());
//                mActiveTab.restoreState(state);
//                load(tabRecrds.get(tabRecrds.size()-1).getUrl());
//            }
//        }

        rbtnMain.setOnCheckedChangeListener(this);
        rbtnMenu.setOnCheckedChangeListener(this);
        rbtnVideo.setOnCheckedChangeListener(this);
        rbtnMulti.setOnCheckedChangeListener(this);
        mTabAdapter = new UCTabAdapter(this, this, mTabs);
        mUCStackView.setAdapter(mTabAdapter);
        mUCStackView.setOnChildDismissedListener(this);
        String num = "" + mTabController.getTabCount();
        tvCaidanMulti.setText(num);
        if (RxNetTool.isNetworkAvailable(this)) {
            fetchFuncs();
            fetchNewsTab();
        } else {
            try {
                tvTempLocation.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                tvTempLocation.getPaint().setAntiAlias(true);
                tvTempLocation.setVisibility(View.VISIBLE);
                tvTempLocation.setText("网络不可用，点击设置网络\n获取天气");
                String newTabsStr = SPUtil.get(this, "homeTabsStr", getResources().getString(R.string.homeTabsStr).trim());
                PageBean<HomeTab> newsTab = new GsonBuilder().create().fromJson(newTabsStr, new TypeToken<PageBean<HomeTab>>() {
                }.getType());
                showNewsTab(newsTab.getData());
//                MainNewFuncs mainNewFuncs = (MainNewFuncs) getLocalData(MainNewFuncs.class, "mainNewFunc", R.string.mainNewFunc);
                String mainNewsStr = SPUtil.get(this,"mainNewFunc",Constant.navs.trim());

                MainNewFuncs mainNewFuncs = new GsonBuilder().disableHtmlEscaping().create().fromJson(mainNewsStr, MainNewFuncs.class);
                showFuncs(mainNewFuncs);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void requestWeather() {
        rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(grant->{
                    if(grant){
                        locationService.start(this);
                        showToast("正在定位当前城市获取天气，请稍后！");
                    }else{
                        tvTempLocation.setText("点击获取定位权限，查看天气！");
                        tvTempLocation.setVisibility(View.VISIBLE);
                    }

                });
    }

    private void updateAppbarHeight() {
        mAppBarLayout.post(new Runnable() {
            @Override
            public void run() {
                mAppBarHeight = mAppBarLayout.getHeight();
            }
        });
    }

    public void fetchFuncs() {
        if (mainFuncs != null && mainFuncs.size() > 0) return;
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("mobileName", Util.getDeviceDevice());
        params.put("mobileModel", Util.getDeviceModel());
        params.put("uChannel", Util.getChannelName());
        params.put("cVersion", Util.getVersionName());
        params.put("pid", Constant.PID);
        check(params);
        if (presenter != null)
            presenter.fetchFuncs(params);
    }

    ArrayList<MainNewFuncs.AdListBean> mainFuncs1 = new ArrayList<>();
    ArrayList<MainNewFuncs.AdListBean> mainFuncs2 = new ArrayList<>();

    @Override
    public void showFuncs(MainNewFuncs result) {
        searchUrl = result.getSearch_url();
        mainFuncs.addAll(result.getAd_list());
//        mainFuncs.addAll(mainFuncs);
//        mainFuncs.addAll(mainFuncs);
//        mainFuncs.addAll(mainFuncs);
        int size = mainFuncs.size();
        if (size <= 12) {
            mainFuncs1.addAll(mainFuncs);
            NavFuncsFragment navFuncsFragment = new NavFuncsFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable("datas", mainFuncs1);
            bundle.putString("title", "0");
            bundle.putInt("total", 1);
            navFuncsFragment.setArguments(bundle);
            navFuncsFragment.setUiController(this);
            fsNavFuncs.add(navFuncsFragment);
        } else {
            for (int i = 0; i < mainFuncs.size(); i++) {
                if (i < 12) mainFuncs1.add(mainFuncs.get(i));
                else mainFuncs2.add(mainFuncs.get(i));
            }
            NavFuncsFragment navFuncsFragment1 = new NavFuncsFragment();
            Bundle bundle1 = new Bundle();
            bundle1.putString("title", "1");
            bundle1.putInt("total", 2);
            bundle1.putInt("index", 1);
            bundle1.putSerializable("datas", mainFuncs1);
            navFuncsFragment1.setArguments(bundle1);
            navFuncsFragment1.setUiController(this);
            fsNavFuncs.add(navFuncsFragment1);

            NavFuncsFragment navFuncsFragment2 = new NavFuncsFragment();
            Bundle bundle2 = new Bundle();
            bundle2.putString("title", "2");
            bundle2.putInt("total", 2);
            bundle2.putInt("index", 2);
            bundle2.putSerializable("datas", mainFuncs2);
            navFuncsFragment2.setArguments(bundle2);
            navFuncsFragment2.setUiController(this);
            fsNavFuncs.add(navFuncsFragment2);

        }
        navFuncs.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), fsNavFuncs));
        navFuncs.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
                if (i == 0) {
                    if (mainFuncs1 != null) {
                        navFuncs.getLayoutParams().height = Util.getDisplayMetrics().widthPixels / spanCount * ((mainFuncs1.size() - 1) / spanCount + 1) + Util.transPX(size <= 12 ? 0 : 15);
                        navFuncs.requestLayout();
                    }
                } else {
                    if (mainFuncs2 != null) {
                        navFuncs.getLayoutParams().height = Util.getDisplayMetrics().widthPixels / spanCount * ((mainFuncs2.size() - 1) / spanCount + 1);
                        navFuncs.requestLayout();
                    }
                }
            }

            @Override
            public void onPageSelected(int i) {

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

    }

    @Override
    public void showCityId(String cityid) {
        if (presenter != null) presenter.fetchMainContent(cityid);
    }

    @Override
    public void showMainContent(MainContent mainContent) {
        tvTempLocation.setVisibility(View.GONE);
        String sk_temp = mainContent.getSk().getSk_temp();
        String weather_condition = mainContent.getSk_weather().getCondition();
        tvCurTemp.setText(sk_temp+"°");
        tvContry.setText(district);
        tvWearth.setText(weather_condition);
        String iconName = TianqiIconUtil.getIconName(weather_condition);
        ivWeather.setImageBitmap(Util.getBitmap(iconName));
        ivLoc.setVisibility(View.VISIBLE);
        updateAppbarHeight();
    }


    private void fetchNewsTab() {
        if (presenter != null) {
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("appname", getResources().getString(R.string.app_name));
            params.put("pkgname", getActivity().getApplicationContext().getPackageName());
            params.put("app_version", Util.getVersionName());
            params.put("os", 1);
            params.put("osv", Util.getDeviceSDK());
            params.put("imei", SPUtil.get(getActivity(), SPUtil.UUID, ""));
            params.put("anid", "");
            params.put("make", Util.getManufactor());
            params.put("model", Util.getDeviceModel());
            params.put("sw", Util.getDisplayMetrics().widthPixels);
            params.put("sh", Util.getDisplayMetrics().heightPixels);
            params.put("devicetype", 1);
            params.put("ip", "");
            params.put("ua", "X5");
            params.put("conn", NetworkUtils.getNetworkType(getActivity()));
            params.put("carrier", "");
            params.put("lon", "");
            params.put("lat", "");
            params.put("uChannel", Util.getChannelName());
            params.put("pid", Constant.PID);
            presenter.fetchNewsTab(params);
        }
    }

    @Override
    public void setData() {
        Intent intent = getIntent();
        String dataString = intent.getDataString();
        String httpurl = dataString;
        if (!TextUtils.isEmpty(httpurl)) {
            Intent intentUrl = new Intent(this, SearchAct.class);
            intentUrl.putExtra("httpurl", httpurl);
            startActivity(intentUrl);
            finish();
        }
    }

    private void switchToMain() {
        Log.e(TAG, "switchToMain :: mUCRootView.getParent() =:" + mUCRootView.getParent());
        if (mUCRootView.getParent() == null) {
            mContentWrapper.addView(mUCRootView);
        }
        mUCRootView.bringToFront();
        WebView view = mActiveTab.getWebView();
        if (view != null) {
            mContentWrapper.removeView(view);
        }
        mActiveTab.clearTabData();
        mActiveTab.stopLoading();
        mFloatSearchBar.setVisibility(View.GONE);
        llBrowserOper.setVisibility(View.GONE);
        mUCBottomBar.setVisibility(View.VISIBLE);
        mIsInMain = true;
    }

    public void animateShowFromBottomToTop(View view, final Runnable onCompleteRunnable) {
        mContentWrapper.setVisibility(View.VISIBLE);
        ObjectAnimator animator = ObjectAnimator.ofFloat(
                view,
                "translationY",
                ViewUtil.getScreenSize(this).y,
                0);
        animator.setDuration(500);
        animator.start();
        mIsAnimating = true;
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mIsAnimating = false;
                if (onCompleteRunnable != null) {
                    onCompleteRunnable.run();
                }
            }
        });
    }

    /**
     * @param animate 是否有动画，有动画时即UCRootView从下往上移
     */
    private void addTab(boolean animate) {
        Log.e(TAG, "addTab = ;-----------");
        int tabCount = mTabController.getTabCount();
        if (tabCount == getResources().getInteger(R.integer.max_tab_count)) {
            String hint = getResources().getString(R.string.multi_window_hint);
            String hint_content = String.format(hint, getResources().getInteger(R.integer.max_tab_count));
            showToast(hint_content);
            return;
        }
        if (animate) {
            switchToMain();
            mContentWrapper.bringToFront();
            animateShowFromBottomToTop(mContentWrapper, new Runnable() {
                @Override
                public void run() {
                    hideTabs(false); // 把页面管理页隐藏
                    mUCBottomBar.bringToFront();
                    initWindow(); // 更改状态栏颜色
                }
            });
        }
        Tab tab = buildTab();
        mActiveTab = tab;
        mTabController.setActiveTab(mActiveTab);
    }

    private void initWindow() {
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);
        StatusBarUtil.setLightMode(this);


    }

    private void removeTab(int index) {
        mTabController.removeTab(index);
    }

    /**
     * 新建一页并初始化页面，这里的ICON为网站图标，我没资源先用UC代替，title为网站title，key为定义的页面ID
     * previewBitmap 为页面的截图
     * 当新建一页时，让我们的选择页置为新建的这一页，然后下次进入页面管理页时初始化进度
     *
     * @return
     */
    private Tab buildTab() {
        Log.e(TAG, "buildTab = ;-----------");
        return mTabController.createNewTab();
    }

    public void hideTabs(boolean animated) {
        mTabsManagerLayout.setVisibility(View.GONE);
        if (isAnimating()) {
            return;
        }
        if (animated) {
            mUCStackView.animateShow(mTabController.getCurrentPosition(), mContentWrapper, mTabsManagerLayout, false, new Runnable() {
                @Override
                public void run() {
                    mTabsManagerLayout.setVisibility(View.GONE);
                    initWindow();
                }
            });
            View selectedChild = mUCStackView.getSelectedChild();
            if (selectedChild != null) {
                UCTabCard card = selectedChild.findViewById(R.id.ucTabCard);
                card.active(false, 350, 40, null);
            }
        } else {
            initWindow();
        }
        mContentWrapper.setVisibility(View.VISIBLE);
        mUCBottomBar.setVisibility(View.VISIBLE);
        mTabsManagerUIShown = false;
    }

    public boolean isAnimating() {
        return /*mUCRootView.isAnimating() ||*/ mUCStackView.isAnimating() || mIsAnimating;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.e(TAG, "dispatchTouchEvent ::isAnimating =: " + isAnimating());
        if (isAnimating()) {
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }


    VideoListFragment videoFragment;

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.rbtn_main:
                flVideoContainer.setVisibility(View.GONE);
                if (rbtnMain.isChecked()) {
                    rbtnMain.setText("头条");
                    rbtnVideo.setEnabled(false);
                    rbtnVideo.setChecked(false);
                    rbtnVideo.setEnabled(true);
                    canAppBarScroll(false);
                } else {
                    rbtnMain.setText("首页");
                    canAppBarScroll(true);
                }

                break;
            case R.id.rbtn_video:
                if (BuildConfig.UM) {
                    String eventid = "menu-video";
                    MobclickAgent.onEvent(MainActivity.this, eventid, "菜单按钮-视频");
                }
                Logger.e("");
                if (rbtnVideo.isChecked()) {
                    rbtnMain.setEnabled(false);
                    rbtnMain.setChecked(false);
                    rbtnVideo.setEnabled(false);
                    rbtnMain.setEnabled(true);
                    flVideoContainer.setVisibility(View.VISIBLE);
                    flVideoContainer.bringToFront();
                    if (videoFragment == null) {
                        videoFragment = new VideoListFragment();
                        getSupportFragmentManager()
                                .beginTransaction()
                                .add(R.id.fl_video_container, videoFragment)
                                .commitAllowingStateLoss();
                    } else {

                    }
                }

                break;
            case R.id.rbtn_menu:
                if (BuildConfig.UM) {
                    String eventid = "menu-menu";
                    MobclickAgent.onEvent(MainActivity.this, eventid, "菜单按钮-菜单");
                }
                rbtnMenu.setChecked(false);
                showMenu();
                /*if (mUCRootView.getMode() != UCRootView.NEWS_MODE)*/ //showTabs();
                break;
            case R.id.rbtn_multi:
                if (BuildConfig.UM) {
                    String eventid = "Multiwindow-menu";
                    MobclickAgent.onEvent(MainActivity.this, eventid, "多窗口-菜单");
                }
                flVideoContainer.setVisibility(View.GONE);
                rbtnVideo.setChecked(false);
                rbtnVideo.setEnabled(true);
                showTabs();
                rbtnMulti.setChecked(false);
                break;
        }
    }

    private PopupWindow popupWindow;
    int menuSpanCount = 4;//底部菜单列数

    private void showMenu() {
        View pop = View.inflate(this, R.layout.popwindow_menu, null);
        pop.findViewById(R.id.iv_shouqi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startIconAnim(v);
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
        });
        RecyclerView rvOper = pop.findViewById(R.id.rv_oper);
        setMenuOpers(rvOper);
        popupWindow = new PopupWindow(pop, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        if (Build.VERSION.SDK_INT >= 21) popupWindow.setClippingEnabled(false);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setAnimationStyle(R.style.popwindow_anim);
        popupWindow.showAtLocation(findViewById(R.id.container), Gravity.BOTTOM, 0,0);
    }


    private void setMenuOpers(RecyclerView rvOper) {
        rvOper.setLayoutManager(new GridLayoutManager(this, menuSpanCount));
        List<Oper> opers = new ArrayList<>();
        boolean noTrace = SPUtil.get(this, SPUtil.KEY_NOTRACE, false);
        Constant.oper_resIds[4] = noTrace ? R.mipmap.wuhen : R.mipmap.wuhenkai;
        for (int i = 0; i < Constant.oper_titles.length; i++) {
            Oper oper = new Oper(Constant.oper_resIds[i], Constant.oper_titles[i], Constant.opers_clz[i]);
            opers.add(oper);
        }
        final OperAdp adp = new OperAdp(R.layout.item_func_menu, opers);
        rvOper.setAdapter(adp);
//        rvOper.getLayoutParams().height = Util.getDisplayMetrics().widthPixels / menuSpanCount * ((opers.size() - 1) / menuSpanCount + 1) + 10;
        adp.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent();
                switch (Constant.oper_titles[position]) {
                    case "分享":
                        if (BuildConfig.UM) {
                            String eventid = "share-menu";
                            MobclickAgent.onEvent(MainActivity.this, eventid, "分享-菜单");
                        }
                        showShare();
                        setShareListener(MainActivity.this);
                        break;
                    case "多窗口":
                        if (BuildConfig.UM) {
                            String eventid = "Multiwindow-menu";
                            MobclickAgent.onEvent(MainActivity.this, eventid, "多窗口-菜单");
                        }
                        flVideoContainer.setVisibility(View.GONE);
                        rbtnVideo.setChecked(false);
                        rbtnVideo.setEnabled(true);
                        showTabs();
                        break;
                    case "无痕模式":
                        if (BuildConfig.UM) {
                            String eventid = "Incognito-menu";
                            MobclickAgent.onEvent(MainActivity.this, eventid, "无痕-菜单");
                        }
                        SPUtil.put(MainActivity.this, SPUtil.KEY_NOTRACE, !noTrace);
                        break;
                    case "清理痕迹":
                        if (BuildConfig.UM) {
                            String eventid = "traces-menu";
                            MobclickAgent.onEvent(MainActivity.this, eventid, "清理痕迹-菜单");
                        }
                        break;
                    case "设置":
                        if (BuildConfig.UM) {
                            String eventid = "settings-menu";
                            MobclickAgent.onEvent(MainActivity.this, eventid, "设置-菜单");
                        }
                        intent.setClass(MainActivity.this, SettingsAct.class);
                        startActivityForResult(intent, REQUESTCODE_SETTINGS);
                        fontSize = SPUtil.get(MainActivity.this, SPUtil.KEY_FONTSIZE, 15);
                        break;
                    case "收藏列表":
                        if (BuildConfig.UM) {
                            String eventid = "Incognito-menu";
                            MobclickAgent.onEvent(MainActivity.this, eventid, "收藏-菜单");
                        }
                        intent.setClass(MainActivity.this, CollectAct.class);
                        startActivity(intent);
                        break;
                    case "历史记录":
                        if (BuildConfig.UM) {
                            String eventid = "history-menu";
                            MobclickAgent.onEvent(MainActivity.this, eventid, "历史记录-菜单");
                        }
                        intent.setClass(MainActivity.this, HistoryAct.class);
                        startActivity(intent);
                        break;
                    case "下载文件":
                        if (BuildConfig.UM) {
                            String eventid = "downloads-menu";
                            MobclickAgent.onEvent(MainActivity.this, eventid, "下载文件-菜单");
                        }
                        intent.setClass(MainActivity.this, DownloadAct.class);
                        startActivity(intent);
                        break;
                }
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
        });
    }


    /**
     * 进入页面管理界面，用动画改变选择页（可以理解为一张截图）的Y和scale
     */
    public void showTabs() {
        if (isAnimating() || mActiveTab == null) {
            return;
        }
        mActiveTab.capture();
        mTabAdapter.updateData(mTabController.getTabs());
        mTabsManagerLayout.bringToFront();
        mTabsManagerLayout.setVisibility(View.VISIBLE);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.windowGrayL), 0);
        mUCStackView.animateShow(mTabController.getCurrentPosition(), mContentWrapper, mTabsManagerLayout, true, new Runnable() {
            @Override
            public void run() {
                mContentWrapper.setVisibility(View.GONE);
                mUCBottomBar.setVisibility(View.GONE);
                mTabsManagerUIShown = true;
            }
        });
        View selectedChild = mUCStackView.getSelectedChild();
        if (selectedChild != null) {
            UCTabCard card = selectedChild.findViewById(R.id.ucTabCard);
            card.active(true, 350, 40, null);
        }
    }

    @OnClick(R.id.iv_return)
    void clickBackBtn(View view) {
        startIconAnim(view);
        hideTabs(true);
    }

    @OnClick(R.id.iv_add)
    void clickAddTabBtn(View view) {
        startIconAnim(view);
        addTab(true);
    }

    @OnClick(R.id.tv_clear_all)
    void clickRemoveAll(View view) {
        startIconAnim(view);
        tabRecrdDao.deleteAll();
        mTabController.getTabs().clear();
        mUCStackView.removeAllViews();
        if (mUCStackView.getChildCount() <= 0) {
            addTab(true);
        }
    }


    boolean backFlag = false;
    Handler handler = new Handler();

    @Override
    public void onBackPressed() {
        if (!backFlag) {
            backFlag = true;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    backFlag = false;
                }
            }, 3000);
            Util.showToastShort("再按一次退出应用！");
        } else {
            super.onBackPressed();
        }
    }

    private CollectHistoryDao collectHistoryDao;

    private void load(String url) {
        if (mActiveTab != null) {
            mActiveTab.loadUrl(url, null);
            noTrace = SPUtil.get(this, SPUtil.KEY_NOTRACE, false);
            if (!noTrace) {
                List<CollectHistory> histories = collectHistoryDao.queryRaw("where url = ?", new String[]{url});
                CollectHistory bean;
                if (histories.size() == 0) {
                    bean = new CollectHistory();
                    bean.setUrl(url);
                    bean.setDate(new Date().getTime());
                    bean.setType(CollectHistory.TYPE_NET);
                    bean.setTitle(url);
                    bean.setIsHis(true);
                    collectHistoryDao.insert(bean);
                } else {
                    bean = histories.get(0);
                    bean.setDate(new Date().getTime());
                    collectHistoryDao.update(bean);
                }
            }
            switchToTab();
        }
    }

    private void switchToTab() {
        if (mUCRootView.getParent() != null) {
            mContentWrapper.removeView(mUCRootView);
        }
        WebView view = mActiveTab.getWebView();
        Log.e(TAG, "switchToTab ----------" + mUCRootView.getParent() + ",view.getParent()= ;" + view.getParent() + ",view =:" + view.getTitle());
        if (view != null && view.getParent() == null) {
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.getLayoutParams();
            if (lp == null) {
                lp = new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
            }
            lp.topMargin = Util.transPX(74);
//                    getResources().getDimensionPixelSize(R.dimen.dimen_48dp);
            mContentWrapper.addView(view, lp);
        }
        mFloatSearchBar.setVisibility(View.VISIBLE);
        llBrowserOper.setVisibility(View.VISIBLE);
        mUCBottomBar.setVisibility(View.INVISIBLE);
        mIsInMain = false;
    }

    @OnClick({R.id.ivForward, R.id.ivBack, R.id.ivMenu, R.id.flWindowsNum, R.id.ivHome})
    public void onBrowserClick(View view) {
        startIconAnim(view);
        switch (view.getId()) {
            case R.id.ivForward:
                if (mActiveTab.getWebView().canGoBack()) {
                    mActiveTab.getWebView().goBack();
                } else {
                    switchToMain();
                }
                break;
            case R.id.ivBack:
                if (mActiveTab.getWebView().canGoForward()) {
                    mActiveTab.getWebView().goForward();
                }
                break;
            case R.id.ivMenu:
                showMenu();
                break;
            case R.id.flWindowsNum:
                showTabs();
                break;
            case R.id.ivHome:
                switchToMain();
                break;
        }

    }


    @Override
    public void onWebsiteIconClicked(String url) {
        Logger.e("url:" + url);
        load(url);
    }

    @OnClick(R.id.ivFloatSearchRefresh)
    public void onFloatSearchRefresh(View view) {
        startIconAnim(view);
        load(mActiveTab.getUrl());
    }

    @Override
    public void selectTab(Tab tab) {
        if (isAnimating()) {
            return;
        }
        int index = mTabController.getTabPosition(tab);
        mActiveTab = tab;
        mTabController.setActiveTab(mActiveTab);
        if (mActiveTab.checkUrlNotNull()) {
            switchToTab();
        } else {
            switchToMain();
        }
        View selectedChild = mUCStackView.getSelectedChild();
        if (selectedChild != null) {
            UCTabCard card = selectedChild.findViewById(R.id.ucTabCard);
            card.active(false, 350, 40, null);
        }
        mUCStackView.selectTab(index, new Runnable() {
            @Override
            public void run() {
                String url = mActiveTab.getUrl();
                if (!TextUtils.isEmpty(url)) load(url);
                Log.e(TAG, "onSelect ----- mActiveTab.checkUrlNotNull() =:" + mActiveTab.checkUrlNotNull() + "mActiveTab " + mActiveTab.getTitle() + "," + mActiveTab.getUrl());
                mContentWrapper.setVisibility(View.VISIBLE);
                mUCBottomBar.setVisibility(View.INVISIBLE);
                llBrowserOper.setVisibility(View.VISIBLE);
                mTabsManagerLayout.setVisibility(View.GONE);
                initWindow();
            }
        });
        Log.e(TAG, "onSelect :: key =:" + tab.getId());
    }

    @Override
    public void closeTab(Tab tab) {
        try {
            int position = mTabController.getTabPosition(tab);
            List<TabRecrd> tabRecrds = tabRecrdDao.loadAll();
            if (tabRecrds.size() > 0) {
                tabRecrdDao.delete(tabRecrds.get(position));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mUCStackView.closeTab(mTabController.getTabPosition(tab));
    }

    @Override
    public void onTabCountChanged() {
        String num = "" + mTabController.getTabCount();
        mTabNum.setText(num); // 更新页面数量
        tvCaidanMulti.setText(num);
    }

    @Override
    public void onTabDataChanged(Tab tab) {
        mTabAdapter.notifyDataSetChanged();
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public TabController getTabController() {
        return mTabController;
    }

    @Override
    public WebViewFactory getWebViewFactory() {
        return mFactory;
    }


    @Override
    public void onSetWebView(Tab tab, WebView view) {

    }

    @Override
    public void onPageStarted(Tab tab, WebView webView, Bitmap favicon) {
        mFloatSearchProgress.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPageFinished(Tab tab) {
        mFloatSearchProgress.setVisibility(View.INVISIBLE);
        tab.shouldUpdateThumbnail(true);
        mTabAdapter.notifyDataSetChanged();
    }

    @Override
    public void onProgressChanged(Tab tab) {
        mFloatSearchProgress.setProgress(tab.getPageLoadProgress());
    }

    public void onReceivedTitle(Tab tab, String title) {
        mTvFloatSearchTitle.setText(title);
        try {
            List<TabRecrd> tabRecrds = tabRecrdDao.loadAll();
            if (tabRecrds.size() < mUCStackView.getChildCount()) {
                TabRecrd tabRecrd = new TabRecrd(null, tab.getUrl(), tab.getTitle());
                tabRecrdDao.insert(tabRecrd);
            } else {
                TabRecrd tabRecrd = tabRecrds.get(mTabController.getTabPosition(mActiveTab));
                tabRecrd.setUrl(tab.getUrl());
                tabRecrd.setTilte(tab.getTitle());
                tabRecrdDao.update(tabRecrd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onFavicon(Tab tab, WebView view, Bitmap icon) {

    }

    private void onTabClosed(int index) {
        removeTab(index);
        if (mUCStackView.getChildCount() <= 0) {
            addTab(true);
        }
    }

    @Override
    public void onChildDismissed(int index) {
        onTabClosed(index);
    }

    /**
     * 控制appbar的滑动
     *
     * @param isScroll true 允许滑动 false 禁止滑动
     */
    protected void canAppBarScroll(boolean isScroll) {
        View mAppBarChildAt = mAppBarLayout.getChildAt(0);
        AppBarLayout.LayoutParams mAppBarParams = (AppBarLayout.LayoutParams) mAppBarChildAt.getLayoutParams();
        if (isScroll) {
            mAppBarParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED|AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
            mAppBarChildAt.setLayoutParams(mAppBarParams);
        } else {
            mAppBarParams.setScrollFlags(0);
        }
        ll_appbarcontent.setVisibility(isScroll ? View.VISIBLE : View.GONE);
//        mAppBarLayout.setExpanded(!isScroll?true:false);

        isDownRefresh(!isScroll);
        viewPager.setCanScroll(!isScroll);
        mIsScroll = isScroll;
        rlSearch2.setVisibility(isScroll ? View.GONE : View.VISIBLE);
    }

    public void isDownRefresh(boolean isDown) {
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            if (fragment instanceof NewsFragment) {
                ((NewsFragment) fragment).isDownRefresh(isDown);
            }
        }
    }

    @Override
    public void showNewsTab(List<HomeTab> tabList) {
        int size = tabList.size();
        if (size == 0) canAppBarScroll(false);
        for (int i = 0; i < size; i++) {
            HomeTab homeTab = tabList.get(i);
            tabLayout.addTab(tabLayout.newTab());
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(R.layout.custom_tab_item_news);
            NewsFragment fragment = NewsFragment.getInstance(homeTab.getTitle());
            fragments.add(fragment);
        }
        tabLayout.setupWithViewPager(viewPager);
        adp = new MyCustomPagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adp);
        viewPager.setOffscreenPageLimit(fragments.size());
        for (int i = 0; i < adp.getCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(R.layout.custom_tab_item_news);
            TextView textView = tab.getCustomView().findViewById(R.id.tab_text);
            textView.setText(tabList.get(i).getTitle());
            if (i == 0) {
                // 设置第一个tab的TextView是被选择的样式
                setTabItemTextStyle(tab, 15, true);
            } else {
                setTabItemTextStyle(tab, 15, false);

            }
        }
        tabLayout.addOnTabSelectedListener(this);
    }

    public void updateNewsAdp(){
        if(adp!=null)adp.notifyDataSetChanged();
    }

    protected void setTabItemTextStyle(TabLayout.Tab tab, int fontSize, boolean isSelected) {
        tab.getCustomView().findViewById(R.id.tab_text).setSelected(isSelected);
        TextView textView = tab.getCustomView().findViewById(R.id.tab_text);
        textView.setTextSize(fontSize);
        if (isSelected) {
            textView.setTextColor(getResources().getColor(R.color.news_text_selected));
        } else {
            textView.setTextColor(getResources().getColor(R.color.news_text_normal));
        }
        View tabIndicator = tab.getCustomView().findViewById(R.id.tab_indicator);
        if (tabIndicator != null) tabIndicator.setVisibility(isSelected ? View.VISIBLE : View.GONE);
        textView.getPaint().setFakeBoldText(isSelected);
        textView.invalidate();
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        tab.getCustomView().findViewById(R.id.tab_text).setSelected(true);
        setTabItemTextStyle(tab, 15, true);
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        tab.getCustomView().findViewById(R.id.tab_text).setSelected(false);
        setTabItemTextStyle(tab, 15, false);
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    public void showVideoFull() {
        statusbar.setVisibility(View.GONE);
        mUCBottomBar.setVisibility(View.GONE);
        videoFullContainer.bringToFront();
        videoFullContainer.setVisibility(View.VISIBLE);
    }

    public void hideVideoFull() {
        statusbar.setVisibility(View.VISIBLE);
        mUCBottomBar.setVisibility(View.VISIBLE);
        videoFullContainer.setVisibility(View.GONE);
    }

    private ResourcesManager resManager;

    @Override
    public void onClick(View v) {
        resManager.setTitle(getResources().getString(R.string.app_name));
        resManager.setText("一款简单好用的浏览器");
        String url = "https://sj.qq.com/myapp/detail.htm?apkName="+getPackageName();
        resManager.setUrl(url);
        resManager.setTitleUrl(url);
        switch (v.getId()) {
            case R.id.rl_wechat:
                WechatShare wechatShare = new WechatShare(this);
                wechatShare.shareWebpager();
                break;
            case R.id.rl_friends:
                WechatMomentsShare wechatMomentsShare = new WechatMomentsShare(this);
                wechatMomentsShare.shareWebpager();
                break;
            case R.id.rl_qq:
                QQShare qqShare = new QQShare(this);
                qqShare.shareWebPager();
                break;
            case R.id.rl_qqzone:
                QQZoneShare qqZoneShare = new QQZoneShare(this);
                qqZoneShare.shareWebPager();
                break;
        }
        if (popupWindowShared != null) popupWindowShared.dismiss();
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        Util.showToastShort("分享成功!");
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Util.showToastShort("分享失败，请重试！");
    }

    @Override
    public void onCancel(Platform platform, int i) {

    }

    @OnClick(R.id.rl_weather)
    public void onClick() {
        if (BuildConfig.UM) {
            String eventid = "weather-bar";
            MobclickAgent.onEvent(MainActivity.this, eventid, "顶部bar-天气");
        }
//        Intent intent = new Intent(this, SearchAct.class);
//        intent.putExtra("httpurl", "https://apps.apple.com/cn/app/id1468057787");
//        startActivity(intent);
        load("http://app.jinritqyb.com/tianqi/app/down.html?from=uallq");
    }
}
